package org.jeecg.modules.monitoring.j_monitoring.controller;

import java.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.monitoring.j_monitoring.utils.EquipmentUtils;
import org.jeecg.modules.monitoring.j_monitoring.constantConfig.MonitorConstant;
import org.jeecg.modules.monitoring.j_monitoring.entity.*;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MGlVirtualizationClusterMapper;
import org.jeecg.modules.monitoring.j_monitoring.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.monitoring.j_monitoring.service.impl.GatewaySystemFdnServiceImpl;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 虚拟化群集
 * @Author: xiaoyq
 * @Date:   2023-02-23
 * @Version: V1.0
 */
@Api(tags="虚拟化群集")
@RestController
@RequestMapping("/j_monitoring/mGlVirtualizationCluster")
@Slf4j
public class MGlVirtualizationClusterController extends JeecgController<MGlVirtualizationCluster, IMGlVirtualizationClusterService> {
	@Resource
	private MGlVirtualizationClusterMapper mGlVirtualizationClusterMapper;

	 @Autowired
	 private IMGlResourceStorageService glResourceStorageService;

	 @Autowired
	 private IMGlComputingResourceService glComputingResourceService;

	 @Resource
	 private GatewaySystemFdnServiceImpl systemFdnService;

	 @Resource
	 private IMGlVirtualizationClusterService clusterService;
	 /**
	 * 分页列表查询
	 *
	 * @param mGlVirtualizationCluster
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "虚拟化群集-分页列表查询")
	@RequiresPermissions("虚拟化群集:查询")
	@ApiOperation(value="虚拟化群集-分页列表查询", notes="虚拟化群集-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MGlVirtualizationCluster mGlVirtualizationCluster,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Result<Page<MGlVirtualizationCluster>> result=new Result<>();
		Page<MGlVirtualizationCluster> pagelist = new Page(pageNo, pageSize);
		QueryWrapper<MGlVirtualizationCluster> queryWrapper = QueryGenerator.initQueryWrapper(mGlVirtualizationCluster, req.getParameterMap());
		if(mGlVirtualizationCluster.getComputingResourcesId()!=null && !"".equals(mGlVirtualizationCluster.getComputingResourcesId())){
			queryWrapper.inSql("id","SELECT cluster_id from m_gl_computing_resource where id='"+mGlVirtualizationCluster.getComputingResourcesId()+"'");
		}
		List<String> ipList = new ArrayList<>();
		pagelist=mGlVirtualizationClusterMapper.getPageList(pagelist,queryWrapper);
		for (MGlVirtualizationCluster cluster:pagelist.getRecords()){
			cluster.setAssociatedStorageNum("0");
			cluster.setComputingResourcesNum("0");
			cluster.setVirtualMachineNum("0");
			if(StringUtils.isNotBlank(cluster.getAssociatedStorageId())){
				cluster.setAssociatedStorageNum(Integer.toString(cluster.getAssociatedStorageId().split(",").length));
			}

			if(StringUtils.isNotBlank(cluster.getComputingResourcesId())){
				cluster.setComputingResourcesNum(Integer.toString(cluster.getComputingResourcesId().split(",").length));
			}

			if (!cluster.getIsMonitor()){
				cluster.setMonitorStatus(EquipmentUtils.getMonitorStatus(cluster.getWhetherToMonitor()));
			}
			ipList.add(cluster.getIpAddress());
		}

		Map<String,Object> map = systemFdnService.getPingMonitor(ipList);

		if (mGlVirtualizationCluster.getIsMonitor()){
			//查看ping返回值
			clusterService.setMonData(map,pagelist.getRecords());

		}

		result.setCode(200);
		result.setSuccess(true);
		result.setResult(pagelist);
		return result;
	}

	 /**
	  * 列表查询
	  *
	  * @param mGlVirtualizationCluster
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "虚拟化群集-列表查询")
	 @ApiOperation(value="虚拟化群集-列表查询", notes="虚拟化群集-列表查询")
	 @GetMapping(value = "/queryList")
	 @RequiresPermissions("虚拟化群集:查询")
	 public Result<?> queryList(MGlVirtualizationCluster mGlVirtualizationCluster,
									HttpServletRequest req) {
		 Result<List<MGlVirtualizationCluster>> result=new Result<>();
		 QueryWrapper<MGlVirtualizationCluster> queryWrapper = QueryGenerator.initQueryWrapper(mGlVirtualizationCluster, req.getParameterMap());
		 if(mGlVirtualizationCluster.getComputingResourcesId()!=null && !"".equals(mGlVirtualizationCluster.getComputingResourcesId())){
			 queryWrapper.inSql("id","SELECT cluster_id from m_gl_computing_resource where id='"+mGlVirtualizationCluster.getComputingResourcesId()+"'");
		 }
		 List<MGlVirtualizationCluster> dataList=mGlVirtualizationClusterMapper.selectList(queryWrapper);

		 clusterService.getHomeData(dataList);

		 result.setCode(200);
		 result.setSuccess(true);
		 result.setResult(dataList);
		 return result;
	 }

	 /**
	  * 设备地图查询
	  */
	 //@AutoLog(value = "虚拟机(管理)-设备地图查询")
	 @ApiOperation(value="虚拟机集群(管理)-设备地图查询", notes="虚拟机集群(管理)-设备地图查询")
	 @GetMapping(value = "/getDeviceMap")
	 @RequiresPermissions("虚拟化群集:查询")
	 public Result<?> getDeviceMap(
			 @RequestParam(name="id",required=true) String id,
			 HttpServletRequest req) {
		 MGlVirtualizationCluster cluster = this.service.getById(id);
		 JSONArray nodes = new JSONArray();
		 JSONArray edges = new JSONArray();
		 JSONObject result=new JSONObject();
		 result.put("nodes",nodes);
		 result.put("edges",edges);
		 if(cluster==null){
			 return Result.OK(result);
		 }

		 int startX = 0,startY = 0;
		 JSONObject clusterNode = this.service.getDeviceMapById(nodes,edges,startX + MonitorConstant.StepX * 1,startY,id);
		 if (clusterNode == null) {
			 return Result.OK(new JSONObject());
		 }

		 IMGlVirtualMachineService mGlVirtualMachineService = ApplicationContextUtil.getContext().getBean(IMGlVirtualMachineService.class);
		 QueryWrapper<MGlVirtualMachine> queryWrapper = new QueryWrapper<>();
		 queryWrapper.lambda().eq(MGlVirtualMachine::getClusterId,id);
		 List<MGlVirtualMachine> virtualMachines = mGlVirtualMachineService.list(queryWrapper);
		 JSONObject child,edge;//第一个虚拟机
		 HashMap<String,JSONObject> appMap = new HashMap<>();
		 int appCount = 0;
		 int i = 0;
		 int appY = 0;
		 String appId;
		 for (MGlVirtualMachine virtualMachine: virtualMachines){
		 	 //创建应用和虚拟机的关系
			 if(StringUtils.isNotBlank(virtualMachine.getAssociatedApplication())){
				 String[] apps = virtualMachine.getAssociatedApplication().split(",");
				 for (int k = 0; k < apps.length; k++) {
					 appId = "_APP_ID_"+ apps[k];
					 if(appMap.containsKey(appId)){
						 //关联应用
						 child = appMap.get(appId);
					 }
					 else{
						 child = new JSONObject();
						 child.put("category", MonitorConstant.Application);
						 child.put("id",appId);
						 child.put("name",apps[k]);
						 child.put("x",startX + MonitorConstant.StepX * 0);
						 child.put("y",appY);

						 nodes.add(child);

						 appMap.put(appId,child);

						 appY = appY + MonitorConstant.StepY;
					 }


					 edge = new JSONObject();
					 edge.put("source",appId);
					 edge.put("target",virtualMachine.getId());
					 edges.add(edge);
				 }
			 }

			 //虚拟机
			 child = new JSONObject();
			 child.put("category",MonitorConstant.VirtualMachine);
			 child.put("id",virtualMachine.getId());
			 child.put("name",virtualMachine.getName());
			 child.put("x",startX + MonitorConstant.StepX * 1);
			 child.put("y",startY + MonitorConstant.StepY * i);
			 nodes.add(child);


			 //虚拟机和群集的关系
			 edge = new JSONObject();
			 edge.put("source",virtualMachine.getId());
			 edge.put("target",cluster.getId());
			 edges.add(edge);
			 i += 1;
		 }

		 return Result.OK(result);
	 }

	 /**
	  * 设备地图查询
	  */
	 //@AutoLog(value = "虚拟机(管理)-设备地图查询")
	 @ApiOperation(value="虚拟机集群(管理)-设备地图查询", notes="虚拟机集群(管理)-设备地图查询")
	 @GetMapping(value = "/getDeviceTree")
	 @RequiresPermissions("虚拟化群集:查询")
	 public Result<?> getDeviceTree(
			 @RequestParam(name="id",required=true) String id,
			 HttpServletRequest req) {
		 MGlVirtualizationCluster cluster = this.service.getById(id);
		 if(cluster==null){
			 return Result.error("群集数据不存在");
		 }
		 JSONObject clusterNode = this.service.getDeviceTreeById(id);
		 if (clusterNode == null) {
			 return Result.OK(new JSONObject());
		 }

		 IMGlVirtualMachineService mGlVirtualMachineService = ApplicationContextUtil.getContext().getBean(IMGlVirtualMachineService.class);
		 QueryWrapper<MGlVirtualMachine> queryWrapper = new QueryWrapper<>();
		 queryWrapper.lambda().eq(MGlVirtualMachine::getClusterId,id);
		 List<MGlVirtualMachine> virtualMachines = mGlVirtualMachineService.list(queryWrapper);
		 JSONArray result = new JSONArray();
		 JSONObject child,temp,firstNode = null;//第一个虚拟机
		 HashMap<String,JSONObject> appMap = new HashMap<>();
		 JSONArray children;
		 for (MGlVirtualMachine virtualMachine: virtualMachines){
			 if(appMap.containsKey(virtualMachine.getAssociatedApplication())){
				 child = appMap.get(virtualMachine.getAssociatedApplication());
				 children = child.getJSONArray("children");
			 }
			 else{
				 child = new JSONObject();
				 child.put("type","应用");
				 child.put("id","");
				 child.put("name",virtualMachine.getAssociatedApplication());
				 result.add(child);
				 children = new JSONArray();
				 child.put("children",children);
				 appMap.put(virtualMachine.getAssociatedApplication(),child);
			 }
			 temp = new JSONObject();
			 temp.put("type","虚拟机");
			 temp.put("id",virtualMachine.getId());
			 temp.put("name",virtualMachine.getName());
			 if(firstNode==null){
				 firstNode = temp;
				 children = new JSONArray();
				 firstNode.put("children",children);
				 children.add(clusterNode);
			 }
		 }

		 return Result.OK(result);
	 }

	/**
	 *   添加
	 *
	 * @param mGlVirtualizationCluster
	 * @return
	 */
	@AutoLog(value = "虚拟化群集-添加")
	@ApiOperation(value="虚拟化群集-添加", notes="虚拟化群集-添加")
	@RequiresPermissions("虚拟化群集:添加")
	@Transactional(rollbackFor = Exception.class)
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MGlVirtualizationCluster mGlVirtualizationCluster) {
		String associatedStorageId = mGlVirtualizationCluster.getAssociatedStorageId();
		//一个群集可以关联很多存储，所以将存储关系数据存放在m_gl_resource_storage表
		mGlVirtualizationCluster.setAssociatedStorageId("");
		mGlVirtualizationCluster.setAssociatedStorage("");
		service.save(mGlVirtualizationCluster);
		this.glResourceStorageService.batchDealData("QJ",mGlVirtualizationCluster.getId(),associatedStorageId);
		if(mGlVirtualizationCluster.getComputingResourcesId()!=null && !"".equals(mGlVirtualizationCluster.getComputingResourcesId())){
			List<String> idList = Arrays.asList(mGlVirtualizationCluster.getComputingResourcesId().split(","));
			this.glComputingResourceService.batchBindingCluster(mGlVirtualizationCluster.getName(),mGlVirtualizationCluster.getId(),idList);
		}
		else{
			this.glComputingResourceService.batchRelieveCluster(mGlVirtualizationCluster.getId());
		}

		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param mGlVirtualizationCluster
	 * @return
	 */
	@AutoLog(value = "虚拟化群集-编辑")
	@ApiOperation(value="虚拟化群集-编辑", notes="虚拟化群集-编辑")
	@RequiresPermissions("虚拟化群集:编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@Transactional(rollbackFor = Exception.class)
	public Result<String> edit(@RequestBody MGlVirtualizationCluster mGlVirtualizationCluster) {
		String associatedStorageId = mGlVirtualizationCluster.getAssociatedStorageId();
		String computingResourcesId = mGlVirtualizationCluster.getComputingResourcesId();
		//一个群集可以关联很多存储，所以将存储关系数据存放在m_gl_resource_storage表
		mGlVirtualizationCluster.setAssociatedStorageId("");
		mGlVirtualizationCluster.setAssociatedStorage("");
		mGlVirtualizationCluster.setComputingResourcesId("");
		mGlVirtualizationCluster.setComputingResources("");
		service.updateById(mGlVirtualizationCluster);
		this.glResourceStorageService.batchDealData("QJ",mGlVirtualizationCluster.getId(),associatedStorageId);
		if(computingResourcesId!=null && !"".equals(computingResourcesId)){
			List<String> idList = Arrays.asList(computingResourcesId.split(","));
			this.glComputingResourceService.batchBindingCluster(mGlVirtualizationCluster.getName(),mGlVirtualizationCluster.getId(),idList);
		}
		else{
			this.glComputingResourceService.batchRelieveCluster(mGlVirtualizationCluster.getId());
		}
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "虚拟化群集-通过id删除")
	@ApiOperation(value="虚拟化群集-通过id删除", notes="虚拟化群集-通过id删除")
	@RequiresPermissions("虚拟化群集:删除")
	@DeleteMapping(value = "/delete")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		service.removeById(id);
		this.glResourceStorageService.batchRemoveStorage("QJ",id);
		this.glComputingResourceService.batchRelieveCluster(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "虚拟化群集-批量删除")
	@ApiOperation(value="虚拟化群集-批量删除", notes="虚拟化群集-批量删除")
	@RequiresPermissions("虚拟化群集:批量删除")
	@DeleteMapping(value = "/deleteBatch")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		this.service.removeByIds(idList);
		this.glResourceStorageService.batchRemoveStorageByResIds("QJ",idList);
		for (int i = 0; i < idList.size(); i++) {
			this.glComputingResourceService.batchRelieveCluster(idList.get(i));
		}
		return Result.OK("批量删除成功!");
	}

	 /**
	  *  监控
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "虚拟化群集-添加监控")
	 @ApiOperation(value="虚拟化群集-添加监控", notes="虚拟化群集-添加监控")
	 @RequiresPermissions("虚拟化群集:监控")
	 @RequestMapping(value = "/monitor", method = {RequestMethod.POST})
	 @Transactional(rollbackFor = Exception.class)
	 public Result<String> monitor(@RequestParam(name="ids",required=true) String ids) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 if(idList.size()==0){
			 return Result.error("数据为空!");
		 }
		 UpdateWrapper<MGlVirtualizationCluster> updateWrapper = new UpdateWrapper<>();
		 LambdaUpdateWrapper<MGlVirtualizationCluster> lambdaUpdateWrapper = updateWrapper.lambda();
		 idList.forEach(item->lambdaUpdateWrapper.or(qr->qr.eq(MGlVirtualizationCluster::getId,item)));
		 lambdaUpdateWrapper.set(MGlVirtualizationCluster::getWhetherToMonitor,"1");
		 service.update(updateWrapper);
		 return Result.OK("监控添加成功!");
	 }

	 /**
	  *  取消监控
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "虚拟化群集-取消监控")
	 @ApiOperation(value="虚拟化群集-取消监控", notes="虚拟化群集-取消监控")
	 @RequiresPermissions("虚拟化群集:取消监控")
	 @RequestMapping(value = "/unmonitor", method = {RequestMethod.POST})
	 @Transactional(rollbackFor = Exception.class)
	 public Result<String> unmonitor(@RequestParam(name="ids",required=true) String ids) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 if(idList.size()==0){
			 return Result.error("数据为空!");
		 }
		 UpdateWrapper<MGlVirtualizationCluster> updateWrapper = new UpdateWrapper<>();
		 LambdaUpdateWrapper<MGlVirtualizationCluster> lambdaUpdateWrapper = updateWrapper.lambda();
		 idList.forEach(item->lambdaUpdateWrapper.or(qr->qr.eq(MGlVirtualizationCluster::getId,item)));
		 lambdaUpdateWrapper.set(MGlVirtualizationCluster::getWhetherToMonitor,"0");
		 service.update(updateWrapper);
		 return Result.OK("监控取消成功!");
	 }


	 /**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "虚拟化群集-通过id查询")
	@ApiOperation(value="虚拟化群集-通过id查询", notes="虚拟化群集-通过id查询")
	@GetMapping(value = "/queryById")
	@RequiresPermissions("虚拟化群集:查询")
	public Result<MGlVirtualizationCluster> queryById(@RequestParam(name="id",required=true) String id) {
		MGlVirtualizationCluster mGlVirtualizationCluster = service.getById(id);
		if(mGlVirtualizationCluster==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mGlVirtualizationCluster);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mGlVirtualizationCluster
    */
	@RequiresPermissions("虚拟化群集:导出")
    @RequestMapping(value = "/exportXls", method = RequestMethod.GET)
	@ApiOperation(value="虚拟化群集-导出", notes="虚拟化群集-导出")
    public ModelAndView exportXls(HttpServletRequest request, MGlVirtualizationCluster mGlVirtualizationCluster) {
        return super.exportXls(request, mGlVirtualizationCluster, MGlVirtualizationCluster.class, "虚拟化群集");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
	@RequiresPermissions("虚拟化群集:导入")
	@ApiOperation(value="虚拟化群集-导入", notes="虚拟化群集-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MGlVirtualizationCluster.class);
    }

	 @RequiresPermissions("虚拟化群集:查询")
	 @ApiOperation(value="虚拟化群集-分页列表查询", notes="虚拟化群集-分页列表查询")
	 @GetMapping(value = "/analysis")
	 public Result<?> analysis(MGlVirtualizationCluster mGlVirtualizationCluster,
									HttpServletRequest req) {
		return Result.ok(service.analysis(mGlVirtualizationCluster));
	 }

	 @Override
	 protected  void beforeImportExcel(List<MGlVirtualizationCluster> list){
		 list.forEach(item->{
			 if(org.apache.commons.lang.StringUtils.isNotEmpty(item.getPersonLiable())){
				 item.setPersonLiable(item.getPersonLiable().trim());
			 }
		 });
	 }

	 @Override
	 protected void afterImportExcel(List<MGlVirtualizationCluster> list){
		 UpdateWrapper<MGlVirtualizationCluster> updateWrapper = new UpdateWrapper<>();

		 updateWrapper.clear();
		 updateWrapper.lambda().isNull(MGlVirtualizationCluster::getPersonLiableId);
		 updateWrapper.setSql("person_liable_id=(select id from sys_user where person_liable=realname LIMIT 1)");
		 this.service.update(updateWrapper);
	 }
}
